import * as d3 from "d3";

import { useEffect, useRef } from "react";
import Weather, { weathers } from "../../domains/weather";

const LinePlot2 = () => {
  const gx = useRef(null);
  const gy = useRef(null);

  const width = 960;
  const height = 400;
  const marginTop = 20;
  const marginRight = 20;
  const marginBottom = 20;
  const marginLeft = 20;

  const parseDate = d3.timeParse("%Y-%m-%d");
  const xAccessor = (weather: Weather) => parseDate(weather.date);
  const dateDomain = d3.extent(weathers, xAccessor);
  const x = d3.scaleTime(dateDomain as Date[], [
    marginLeft,
    width - marginRight,
  ]);

  const yAccessor = (weather: Weather) => weather.temperatureMax;
  const tempDomain = d3.extent(weathers, yAccessor);
  const y = d3.scaleLinear(tempDomain as [number, number], [
    height - marginBottom,
    marginTop,
  ]);

  const line = d3
    .line<Weather>()
    .x((d) => x(parseDate(d.date)!))
    .y((d) => y(d.temperatureMax));

  useEffect(() => void d3.select(gx.current).call(d3.axisBottom(x)), [gx, x]);
  useEffect(() => void d3.select(gy.current).call(d3.axisLeft(y)), [gy, y]);

  return (
    <svg width={width} height={height}>
      <g ref={gx} transform={`translate(0,${height - marginBottom})`} />
      <g ref={gy} transform={`translate(${marginLeft},0)`} />
      <path
        fill="none"
        stroke="currentColor"
        strokeWidth="1.5"
        d={line(weathers)!}
      />
      <g fill="white" stroke="currentColor" strokeWidth="1.5">
        {weathers.map((d, i) => (
          <circle key={i} cx={x(xAccessor(d)!)} cy={y(yAccessor(d))} r="2.5" />
        ))}
      </g>
    </svg>
  );
};

export default LinePlot2;
